/*
 * HSM Proxy Project.
 * Copyright (C) 2013 FedICT.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License version
 * 3.0 as published by the Free Software Foundation.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, see 
 * http://www.gnu.org/licenses/.
 */

package be.fedict.hsm.admin.webapp.security;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.security.Principal;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import be.fedict.hsm.model.security.SecurityFunction;

@Interceptor
@RolesAllowed
@SecurityFunction("SF.I&A.2")
public class SecurityInterceptor implements Serializable {

	private static final long serialVersionUID = 1L;

	private static final Log LOG = LogFactory.getLog(SecurityInterceptor.class);

	@AroundInvoke
	public Object securityVerification(InvocationContext invocationContext)
			throws Exception {
		Method method = invocationContext.getMethod();
		Class<?> clazz = invocationContext.getMethod().getDeclaringClass();
		LOG.trace("security verification: " + clazz.getSimpleName() + "."
				+ method.getName());
		RolesAllowed rolesAllowedAnnotation = method
				.getAnnotation(RolesAllowed.class);
		if (null == rolesAllowedAnnotation) {
			rolesAllowedAnnotation = clazz.getAnnotation(RolesAllowed.class);
		}
		String[] allowedRoles = rolesAllowedAnnotation.value();

		FacesContext facesContext = FacesContext.getCurrentInstance();
		ExternalContext externalContext = facesContext.getExternalContext();
		HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext
				.getRequest();
		Principal userPrincipal = httpServletRequest.getUserPrincipal();
		if (null == userPrincipal) {
			throw new SecurityException("user not logged in");
		}

		boolean userInRole = false;
		for (String allowedRole : allowedRoles) {
			if (httpServletRequest.isUserInRole(allowedRole)) {
				LOG.trace("user in role: " + allowedRole);
				userInRole = true;
				break;
			}
		}
		if (false == userInRole) {
			throw new SecurityException("user not in allowed roles");
		}

		return invocationContext.proceed();
	}
}
